package com.vinaprime.primeschedule.presentation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class VPEventMap extends Activity {
	private GoogleMap googleMap ;
	private ApplicationInformation info;
	private String path;
	AutoCompleteTextView _autoTextView;
	private Geocoder geocoder;
	private ArrayAdapter<String> adapter;
	private ArrayList<String> listAddress; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpevent_map);
		/*Khoi tao Geocoder*/
		geocoder = new Geocoder(getApplicationContext());
		
		googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
		googleMap.setMyLocationEnabled(true);
		googleMap.setBuildingsEnabled(true);
		GoogleMapOptions options = new GoogleMapOptions();
		options.mapType(GoogleMap.MAP_TYPE_SATELLITE)
	    .compassEnabled(true)
	    .rotateGesturesEnabled(true)
	    .tiltGesturesEnabled(true)
	    ;
		LatLng HCM = new LatLng(10.78, 106.70);
		googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(HCM, 13));

		googleMap.addMarker(new MarkerOptions()
                .title("Ho Chi Minh").snippet("The most populous city in Viet Nam.")
                .position(HCM));		
		;
		
		/*Khoi dong search view - action bar*/
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.drawable.background_top_shape_green);  
		actionBar.setBackgroundDrawable(d);	

    	actionBar.setCustomView(R.layout.activity_filter_auto_complete_search_view);
    	
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
		_autoTextView = (AutoCompleteTextView)findViewById(R.id.autoComplete_SearchFilter);		
    	
		try {
			Toast.makeText(getApplicationContext(),""+ geocoder.getFromLocationName("HCM, Viet Nam", 1).get(0).getCountryName().toString(), Toast.LENGTH_LONG).show();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//showArrayAdapter();
		listAddress = new ArrayList<String>();
		try {
        	List<Address> listAdd = geocoder.getFromLocationName("Quan 3, TPHCM", 5);
			
			for(int i=0; i<listAdd.size();i++){
				Address addr = listAdd.get(i);
				StringBuilder str = new StringBuilder();				

				
				for(int j=0;j<addr.getMaxAddressLineIndex();j++){
					str.append(addr.getAddressLine(j)).append(", ");
				}
				listAddress.add(str.toString());
				Toast.makeText(getApplicationContext(), str.toString(), Toast.LENGTH_LONG).show();
			}			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, listAddress);
		//_autoTextView.setAdapter(adapter);
		
		info = new ApplicationInformation(getApplicationContext());
		path = info.getDBPath();

	}
    public Bitmap takeScreenShot(){
    	View rootview = findViewById(R.id.map).getRootView();
    	rootview.setDrawingCacheEnabled(true);
    	return rootview.getDrawingCache();
    }
    public void saveBitmap (Bitmap bitmap,String path){
    	File imagepath =  new File(path);
    	FileOutputStream fos;
    	try{
    		fos = new FileOutputStream(imagepath);
    		bitmap.compress(CompressFormat.JPEG, 100, fos);
    		fos.flush();
    		fos.close();
    	}catch(Exception e){
    		e.getMessage();
    	}
    }
    public void showArrayAdapter(){   
    	
    	try {
        	List<Address> listAdd = geocoder.getFromLocationName(_autoTextView.getText().toString(), 5);
			
			for(int i=0; i<listAdd.size();i++){
				Address addr = listAdd.get(i);
				StringBuilder str = new StringBuilder();
				
				for(int j=0;j<addr.getMaxAddressLineIndex();j++){
					str.append(addr.getAddressLine(j)).append(", ");
				}
				listAddress.add(str.toString());
				Toast.makeText(getApplicationContext(), str.toString(), Toast.LENGTH_LONG).show();
			}			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, listAddress);
		_autoTextView.setAdapter(adapter);
		
    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vpevent_map, menu);
		return true;
	}
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.take_image:
	    	 
	    	//String text =showListNamefromDir(info.getDBPath()+"images/");  
	    	//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
	    	//Log.d("Content of Path", text);
	    	
	    	AssetManager asset = getResources().getAssets();
	    	File folder = new File(path+"images");
	    	if (!folder.exists()){
	    		if(folder.mkdir()){
	    			Toast.makeText(getApplicationContext(), "Images Exist", Toast.LENGTH_LONG).show();
	    			Log.d("Tao Folder", "OK");
	    		}else{
	    			Log.d("Tao Folder", "Error");
	    		}
	    		
	    	}
	    	else{
	    		Log.d("Tao Folder", "Exist!");
	    	}
	    	//Save Images
	    	final String filename = "map_"+ String.valueOf(System.currentTimeMillis()) + ".jpg";
	    	Bitmap bitmap = takeScreenShot();
	    	saveBitmap(bitmap, path+"images/" + "map_"+ filename);	  
	    	/*
			 * Hien thi Alert
			 * */
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
	        alert.setTitle("Rename");       
	        final EditText input  = new EditText(this);          
	        input.setText(filename);
	        alert.setView(input);
	        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					//Toast.makeText(getApplicationContext(), "Current File Name:"+FileName, Toast.LENGTH_LONG).show();
					String value = input.getText().toString().trim();
					File from      = new File(path+"images/", filename);
				    File to        = new File(path+"images/", value);
				    boolean renameSuccess = from.renameTo(to);		
				  
				}
			});
	        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();						
				}
	        });
	        alert.show();	        	
							
	      break;
	    
	    default:
	    	break;
	    }
	    return true;
	  } 
	public String showListNamefromDir(String path){
		String Result = "";
		File file;
		List<String> myList = new ArrayList<String>();		
		file = new File(path);
		File list[] = file.listFiles();
		for (int i = 0; i< list.length;i++){
			myList.add(list[i].getName());
			Result = Result + "-"+ list[i].getName();
		}		
		
		return Result;
	}

	protected boolean isRouteDisplayed() {
        return false;
    }
}
